package com.miniboy.imageloader.util;

import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 作者 ${郭鹏飞}.<br/>
 */
public class MD5Util {

    public static final int TYPE_UPPER_CASE = 0x0001;
    public static final int TYPE_LOWER_CASE = 0x0002;

    private MD5Util() {
    }

    /**
     * 对数据进行MD5处理
     *
     * @param source 源数据
     * @return 处理以后的数据
     */
    public static String format(String source) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("md5");
            md5.update(source.getBytes());
            return bytes2HexString(md5.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String bytes2HexString(byte[] data) {
        if (data == null || data.length <= 0) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (byte b : data) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                sb.append("0");
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 对数据进行MD5处理,并且进行大小写格式化
     *
     * @param source 源数据
     * @param type   目标数据大小写处理 {@link #TYPE_LOWER_CASE}或者{@link #TYPE_UPPER_CASE}
     * @return 处理以后的数据
     */
    public static String format(String source, int type) {
        if (TextUtils.isEmpty(source)) {
            throw new NullPointerException("源数据为空");
        }
        if (type != TYPE_UPPER_CASE && type != TYPE_LOWER_CASE) {
            throw new IllegalArgumentException("类型参数指定非法");
        }
        String target = format(source);
        if (TextUtils.isEmpty(target)) {
            return null;
        }
        return type == TYPE_UPPER_CASE ? target.toUpperCase() : target.toLowerCase();
    }
}
